const libPath = './build/demo';
const Module = require(libPath);
const wasm = Module({ wasmBinaryFile: libPath });

console.clear();
wasm.then((instance) => {
    // 返回int
    console.log('返回int', instance.sum(100, 20));
    // 返回char
    console.log('返回char', instance._getChar());
    // 返回int
    console.log('roll_dice', instance._roll_dice());
    // 返回数组
    console.log('返回数组');
    array_from_wasm(instance);

    // 一个int，返回一个int
    console.time('instance._fibonacci_recursive');
    console.log('instance._fibonacci_recursive', instance._fibonacci_recursive(35));
    console.timeEnd('instance._fibonacci_recursive');

    // 对比js版本的性能指标
    console.time('js fibonacci_recursive');
    console.log('js fibonacci_recursive: ', fibonacci_recursive(35));
    console.timeEnd('js fibonacci_recursive');

    // 使用c++的class
    const cppClass = new instance.MyClass(10, 'hello');
    cppClass.incrementX();
    console.log('cppClass.x', cppClass.x);
    cppClass.x = 20;
    console.log('cppClass.x', cppClass.x);
    console.log(
        'instance.MyClass.getStringFromInstance(cppClass)',
        instance.MyClass.getStringFromInstance(cppClass)
    );
    cppClass.delete();

    // 使用c++ vector
    const vec = instance.getVector();
    console.log('vec.size', vec.size());
    for (let i = 0; i < vec.size(); i++) {
        console.log(`vec ${i}`, vec.get(i));
    }

    // 使用 c++ Struct
    const obj = instance.getUser();
    console.log('getUser', obj);

    const obj2 = instance.setUser({
        name: 'X',
        age: 3,
    });
    console.log('setUser', obj2);
});

function array_from_wasm(instance) {
    const lengthPtr = instance._malloc(4); // 分配内存存储数组长度（4字节用于int）

    // 调用 Wasm 函数获取数组指针和长度
    const arrayPtr = instance._getArray(lengthPtr);
    const length = instance.HEAP32[lengthPtr / 4]; // 从线性内存中读取长度值

    // 从线性内存中获取数组数据
    const array = [];
    for (let i = 0; i < length; i++) {
        array.push(instance.HEAP32[arrayPtr / 4 + i]);
    }

    console.log('Array from Wasm:', array);

    // 释放分配的内存
    instance._free(lengthPtr);
}

function fibonacci_recursive(n) {
    if (n <= 1) return n;
    return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
